from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render
import os
from myweb.message import testJson
from myweb.Helper import returnJson, saveUploadFile, getDefaultContext, detectImage, getContextResult, getYoloPath, round_floats
import json

def index(request):##跳转到登陆界面
    return render(request, 'myweb/login.html')
    # return HttpResponse('Hello World!')




## 调用 种子发芽
def detect(request):##主要界面，跳转到检测种子界面
    return render(request, 'myweb/detectImage.html')
    # return render(request, 'static/tabs.html')




def test(request):##测试用
    context = {
        'news_list': [
            {
                "title": "图雀写作工具推出了新的版本",
                "content": "随随便便就能写出一篇好教程，真的很神奇",
            },
            {
                "title": "图雀社区正式推出快速入门系列教程",
                "content": "一杯茶的功夫，让你快速上手，绝无担忧",
            },
        ]
    }

    return render(request, 'myweb/test.html', context=context)
    # return HttpResponse('Hello World!!!!!')


#########################################################################################
### 核心 处理
# from django.views.decorators.csrf import csrf_exempt
# OK：用作表单提交图片处理，进行YOLO，并返回结果到
def uploadForm(request): # 测试用
    context = getDefaultContext()

    bFile, imagePath = isUploadFileReady(request)
    if bFile == False:
        return render(request, 'myweb/seedresult.html', context=context)

    isImg = False# 以方格图 与 种子标注来绘图
    data = detectImage(imagePath, isImg)##调用Helper

    context = getContextResult(*data, isImg)##调用Helper
    return render(request, 'myweb/seedresult.html', context=context)

##以Ajax方式返回， 系统上的主要用法
def uploadAjax(request):
    context = getDefaultContext()

    bFile, imagePath = isUploadFileReady(request)
    if bFile == False:
        return HttpResponse(json.dumps(context))

    width = request.POST.get('width', '0')#2023-06-03 增加原始图片尺寸保存，解决图片显示与 保存处理大小不一致
    height = request.POST.get('height', '0')

    isImg = False
    data = detectImage(imagePath, isImg, (int(width), int(height)))##调用Helper

    context = getContextResult(*data, isImg)##调用Helper

    # json.encoder.FLOAT_REPR = lambda x: format(x, '.1f')  # 没有
    return HttpResponse(json.dumps(round_floats(context)))

##用作笔记本处理测试数据
def testAjax(request):
    fileName = 'static/test.json'
    fileName = os.path.join(os.getcwd(), fileName).replace('\\', '/')
    print(fileName)
    data = ''
    with open(fileName, 'r', encoding = "utf-8") as f:
        data = f.read()
    #print('data:', data)
    return HttpResponse(data)

def uploadDetect(request):  ##由 /upload2转入
    action = request.POST.get('action', None)
    print('uploadDetect:', action)
    if action == 'ajax':
        return uploadAjax(request)
    elif action == 'test':
        return testAjax(request)
    else:
        return uploadForm(request)

##处理上传文件
def isUploadFileReady(request):
    if request.method != "POST":
        print('uploadAjax, request.method != POST.............')
        return False, ''

    bFile, imagePath = saveUploadFile(request)  ##复制文件
    if bFile == False:
        print('upload2, bFile == False.............')
        return False, ''

    # print('upload2, bFile == True.............')
    return bFile, imagePath



############################################################################
## 测试用
def upload(request):
    if request.method == "POST":
        user = request.POST.get('user', None)
        if user is not None:
            print("user is existing.....")
        else:
            print("user is None.....")


        file = request.FILES.get("file", None)

        if file is None:
            return HttpResponse("no files for upload!")

        # print(file)

        import os
        image_path = 'tmp/%s' % file.name
        # 开启一个流
        image_path = os.path.join(os.getcwd(), image_path).replace('\\', '/')

        with open(image_path, 'wb+') as f:
            # 分块写入文件;
            for chunk in file.chunks():
                f.write(chunk)
            f.close()
        file.close()

        import os
        print(file.name)
        statinfo = os.stat(image_path)
        print(statinfo.st_size)

        ret = testJson(request)
        context = {
            'fileSize' : statinfo.st_size,
            'fileName' : file.name,
            'json'     : ret,
        }
        return render(request, 'myweb/success.html', context)
    else:
        return HttpResponse("no files for upload!222222")


    # return render(request, 'myweb/test.html')

#############################################################################
#############################################################################
# 测试调用yolov5s工程的test_img_call.py文件
# 纯碎测试，不是实际调用，实际调用在Helper哪里
def testCall(request):
    import sys
    sys.path.append(getYoloPath())
    import test_img_call as tt
    res = tt.aaaaa()

    fileImageName = '97w.jpg'
    image_path = 'tmp/%s' % fileImageName
    image_path = os.path.join(os.getcwd(), image_path).replace('\\', '/')

    stat, imgcv, detects, fileSaveDrawBox = tt.test_from_web(image_path, '',
                                                             isSaveFiles=False,
                                                             isSaveImg=False,
                                                             shrink_image=True)
    baseWebPath = os.getcwd().replace('\\', '/')

    fileImageWebPath = fileSaveDrawBox.replace(baseWebPath, '')
    print('testCall:', fileImageWebPath)
    print('testCall:', baseWebPath)
    jsonStr = returnJson(stat, imgcv, detects, fileSaveDrawBox, fileImageWebPath)
    res2 = '111'
    return HttpResponse("return:" + jsonStr)



